<?php


/**
 * Zender
 *
 * @category   Zender
 * @package    Zender
 * @subpackage Zender_Core
 * @author ximarx
 * @version 0.0.0
 */

/**
 * @category   Zender
 * @package    Zender
 * @subpackage Zender_Core
 */
class Zender_Config_Db extends Zend_Config {
	
	public function __construct(Zender_Config_Db_Table $table, $allowModifications = false) {
		$preProcessedArray = $table->getConfigsAsArray();
		$dataArray = $this->_processKey($preProcessedArray);
		parent::__construct($dataArray, $allowModifications);		
	}
	
    /**
     * Convert array from rowset in a valid array for Zend_Config
     *
     * @param array $dataArray
     * @throws Zend_Config_Exception
     * @return array
     */
    protected function _processKey(array $dataArray) {
    	
    	$processedArray = array();
    	foreach ($dataArray as $key => $value) {
    		$exploded = explode('.', $key);
    		if ( count($exploded) == 1 ) {
    			$processedArray[$key] = $value;
    		} else {
	    		$realKey = $exploded[0];
	    		array_shift($exploded);
	    		$imploded = implode('.', $exploded);
	    		if ( array_key_exists($realKey, $processedArray)) {
	    			if ( !is_array($processedArray[$realKey]) ) {
	    				throw new Zend_Config_Exception("Cannot create sub-key for '{$realKey}' as key already exists");
	    			}
	    			$processedArray[$realKey] = array_merge($processedArray[$realKey], $this->_processKey(array($imploded => $value)));
	    		} else {
	    			$processedArray[$realKey] = $this->_processKey(array($imploded => $value));
	    		}
    		}
    	}
    	return $processedArray;
    }

}
